var express = require('express');
var router = express.Router();
//引入注册接口模块
var {userModel} =  require('../database/model/clientModel')
var bcrypt = require('bcryptjs') // 引入bcryptjs
var salt = bcrypt.genSaltSync(10); //生成加密盐
var jwt = require('jsonwebtoken')  //引入token
var secret = 'asdfasdfasdfas46546asdfasdf654a6sdfa' //私钥



router.post('/', function(req, res, next) {//注册接口
  console.log(req.body);
  let {password,username,phone,email} = req.body
  userModel.find({username}).then(result=>{
    console.log(111,result);
    if(result.length){ //判断账号是否存在
      res.send({
        code:100,
        msg:'账号已存在'
      })
      return 
    }
    let hash = bcrypt.hashSync(password,salt)  //加密密码
    new userModel ({ //向数据库提交数据
      username:username,
      phone:phone,
      email:email,
      password:hash
    }).save().then(result=>{
      console.log(result)
      res.send({
        code:101,
        msg:'注册成功'
      })
    })
  })
});

//登录
router.get('/', function(req, res, next) {
  console.log(req.query)
  let {password,username} = req.query
  userModel.find({username}).then(result=>{
    console.log(222,result)
    if(!result.length){ //判断账号是否存在
      res.send({
        code:100,
        msg:'账号不存在，请注册'
      })
      return
    }
    let hash = result[0].password //得到用户的加密密码
    console.log(hash,333)
    let bool = bcrypt.compareSync(password,hash)
    if(!bool){
      res.send({
        code:102,
        msg:'密码错误，请重试'
      })
      return
    }
    let token = jwt.sign({ //签发token
      time:Date.now(),//签发时间
      expire:1000*60*60*24*7 //有效时长
    },secret)
    
    let {username,avatar,phone,_id,email} = result[0]
    res.send({
      code:101,
      msg:'登陆成功',
      data:{_id,username,avatar,phone,token,email}
    })
  })
});

const multer  = require('multer')
// 方法2：自主定义存放路径、图片名称
const storage = multer.diskStorage({
  destination: function (req, file, cb) { //定义存放路径
    cb(null, 'public/images')
  },
  filename: function (req, file, cb) { //定义图片名称
    const name = Date.now() + Math.random().toString(36).substring(2)
    // console.log(file);
    let type = file.mimetype.split('/')[1] //提取图片后缀
    cb(null, `${name}.${type}`)
  }
})
const upload = multer({ storage: storage })
router.post('/upload',upload.single('avatar'),(req,res)=>{
  console.log(333,req.file);
  res.send({
    code:1,
    msg:'上传成功',
    data:{
      url:`/images/${req.file.filename}`
    }
  })
})

//更新头像
router.put('/',(req,res)=>{  //更新用户信息
  console.log(req.body);
  let {_id,info} = req.body
  userModel.update({_id},info).then(result=>{
    res.send({
      code:101,
      msg:'更新成功'
    })
  })
})

module.exports = router;
